package reset

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
)

// todo 需要为cas-agent适配自定义目录
func CreateCASResetScripts(datadir string) error {
	if datadir == "" {
		datadir = "/root/iscas"
	}
	err := CreateCasKillAllScripts(datadir)
	if err != nil {
		return err
	}
	err = CreateCasUninstallScripts(datadir)
	if err != nil {
		return err
	}
	return nil
}

func CreateCasKillAllScripts(datadir string) error {

	content := fmt.Sprintf(`
#!/bin/sh

[ $(id -u) -eq 0 ] || exec sudo $0 $@

set -x

for service in /etc/systemd/system/cas*.service; do
    [ -s $service ] && systemctl stop $(basename $service)
done

for service in /etc/init.d/cas*; do
    [ -x $service ] && $service stop
done

pschildren() {
    ps -e -o ppid= -o pid= | \
    sed -e 's/^\s*//g; s/\s\s*/\t/g;' | \
    grep -w "^$1" | \
    cut -f2
}

pstree() {
    for pid in $@; do
        echo $pid
        for child in $(pschildren $pid); do
            pstree $child
        done
    done
}

killtree() {
    kill -9 $(
        { set +x; } 2>/dev/null;
        pstree $@;
        set -x;
    ) 2>/dev/null
}

remove_interfaces() {
    # Delete network interface(s) that match 'master cni0'
    ip link show 2>/dev/null | grep 'master cni0' | while read ignore iface ignore; do
        iface=${iface%%@*}
        [ -z "$iface" ] || ip link delete $iface
    done

    # Delete cni related interfaces
    ip link delete cni0
    ip link delete flannel.1
    ip link delete flannel-v6.1
    ip link delete kube-ipvs0
    ip link delete flannel-wg
    ip link delete flannel-wg-v6
	ip link delete hostSideIface
	
    # Restart tailscale
    if [ -n "$(command -v tailscale)" ]; then
        tailscale set --advertise-routes=
    fi
}
IF_CONTAINERD=true
getshims() {
	ps -e -o pid= -o args= | sed -e 's/^ *//; s/\s\s*/\t/;' | grep -w 'containerd-shim' | grep -- '-namespace k8s.io' | cut -f1
}

killtree $({ set +x; } 2>/dev/null; getshims; set -x)

do_unmount_and_remove() {
    set +x
    while read -r _ path _; do
        case "$path" in $1*) echo "$path" ;; esac
    done < /proc/self/mounts | sort -r | xargs -r -t -n 1 sh -c 'umount -f "$0" && rm -rf "$0"'
    set -x
}

do_unmount_and_remove '%s/data/cas/kubelet/pods'
do_unmount_and_remove '%s/data/cas/kubelet/plugins'
do_unmount_and_remove '/run/netns/cni-'

# Remove CNI namespaces
ip netns show 2>/dev/null | grep cni- | xargs -r -t -n 1 ip netns delete

remove_interfaces

rm -rf /var/lib/cni/
iptables-save | grep -v KUBE- | grep -v CNI- | grep -iv flannel | iptables-restore
ip6tables-save | grep -v KUBE- | grep -v CNI- | grep -iv flannel | ip6tables-restore
`, datadir, datadir)

	filePath := filepath.Join(datadir, "data", "cas", "scripts", "cas-killall.sh")

	// 创建文件所在的文件夹，如果它不存在
	//dir := os.DirFS(filePath)
	if _, err := os.Stat(filepath.Dir(filePath)); os.IsNotExist(err) {
		err := os.MkdirAll(filepath.Dir(filePath), 0755) // 使用0755权限
		if err != nil {
			logrus.Errorf("Failed to create directory: %s", err)
			return err
		}
	}

	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0777) // 使用0644权限
	if err != nil {
		logrus.Errorf("Failed to open or create file: %s", err)
	}
	defer file.Close()

	if _, err := file.WriteString(content); err != nil {
		logrus.Errorf("Failed to write to file: %s", err)
		return err
	}
	return nil
}

func CreateCasUninstallScripts(datadir string) error {

	content := fmt.Sprintf(`
#!/bin/sh
set -x
[ $(id -u) -eq 0 ] || exec sudo $0 $@

%s/data/cas/scripts/cas-killall.sh

if command -v systemctl; then
    if [ -f /etc/systemd/system/cas.service ]; then
        systemctl disable cas
        systemctl daemon-reload
        rm -f /etc/systemd/system/cas.service
        rm -f /etc/systemd/system/cas.service.env
    fi

    if [ -f /etc/systemd/system/cas-agent.service ]; then
        systemctl disable cas-agent
        systemctl daemon-reload
        rm -f /etc/systemd/system/cas-agent.service
        rm -f /etc/systemd/system/cas-agent.service.env
    fi
fi
if command -v rc-update; then
	if [ -f /etc/systemd/system/cas.service ]; then
        rc-update delete cas default
    fi
    if [ -f /etc/systemd/system/cas-agent.service ]; then
        rc-update delete cas-agent default
    fi
fi

remove_uninstall() {
    rm -rf /run/flannel
	rm -rf %s/config/cas
	rm -rf %s/logs/cas 
	rm -rf %s/data/cas
	rm -rf /usr/bin/cas
}
trap remove_uninstall EXIT

if (ls /etc/systemd/system/cas*.service || ls /etc/init.d/cas*) >/dev/null 2>&1; then
    set +x; echo 'Additional cas services installed, skipping uninstall of cas'; set -x
    exit
fi

#for cmd in kubectl crictl ctr; do
#    if [ -L /usr/local/bin/$cmd ]; then
#        rm -f /usr/local/bin/$cmd
#    fi
#done

if type yum >/dev/null 2>&1; then
    yum remove -y cas
    rm -f /etc/yum.repos.d/*cas*.repo
elif type rpm-ostree >/dev/null 2>&1; then
    rpm-ostree uninstall k3s-selinux
    rm -f /etc/yum.repos.d/*cas*.repo
fi
`, datadir, datadir, datadir, datadir)

	filePath := filepath.Join(datadir, "data", "cas", "scripts", "cas-uninstall.sh")

	// 创建文件所在的文件夹，如果它不存在
	//dir := os.DirFS(filePath)
	if _, err := os.Stat(filepath.Dir(filePath)); os.IsNotExist(err) {
		err := os.MkdirAll(filepath.Dir(filePath), 0755) // 使用0755权限
		if err != nil {
			logrus.Errorf("Failed to create directory: %s", err)
			return err
		}
	}

	// 打开或创建文件，如果文件不存在
	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0777) // 使用0644权限
	if err != nil {
		logrus.Errorf("Failed to open or create file: %s", err)
	}
	defer file.Close()

	// 写入内容
	if _, err := file.WriteString(content); err != nil {
		logrus.Errorf("Failed to write to file: %s", err)
		return err
	}
	return nil
}
